package com.qf.springboot.demoredis.service.Impl;

import com.qf.springboot.demoredis.lock.DistributeRedisLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Auther: Adrian
 * @Date: 2020/3/9 18:39
 * @Description:
 */

@Service
public class TrainTickService {
    private Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private DistributeRedisLock distributeRedisLock;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    public String produceStockRedisson(){
        String lock="lock";
        try {
            boolean lock1 = distributeRedisLock.lock(lock);
            if(true==lock1){//说明加锁成功
                int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("movietickes"));
                //首先要判断下 这个库存是否>0
                if (stock > 0) {  //说明可以减去库存
                    int rStock = stock - 1;
                    //下一步：将真实的库存放到咋们的Redis中去
                    stringRedisTemplate.opsForValue().set("movietickes", String.valueOf(rStock));
                    logger.info("扣减库存成功....剩余库存:" + rStock);

                } else {   //说明不能扣减库存
                    logger.info("库存扣减失败、库存是负数、不足...");
                }  //已经用了15秒钟
            }else{
                return "当前的排队人数过多...";
            }
        }finally {
            distributeRedisLock.unlock(lock);
        }
        return "抢票成功....";
    }
}
